<template>
  <div class="login-container">
    <van-nav-bar class="app-nav-bar" title="注册/登录" left-arrow @click-left="router.back" />
    <van-form ref="loginForm" @submit="onLogin" @failed="onFailed" :show-error="false" :show-error-message="false">
        <van-field  center name="mobile" v-model="user.mobile" icon-prefix="toutiao"  left-icon="shouji" right-icon="" placeholder="请输入手机号" :rules="formRules.mobile"></van-field>
        <van-field center name="code" v-model="user.code" icon-prefix="toutiao"  left-icon="yanzhengma" right-icon="" placeholder="请输入验证码" :rules="formRules.code">
            <template #button>
                <van-count-down  @finish="isCountDownShow = false" v-if="isCountDownShow" :time="1000 * 60" format="ss s" />
                <van-button :loading="isSendSmsLoading" v-else class="send-btn" @click.prevent="onSendSMS" size="small" round>获取验证码</van-button>
            </template>
        </van-field>
        <div class="login-btn-wrap">
            <van-button class="login-btn" type="primary" native-type="submit"  block>登录</van-button>
        </div>
    </van-form>

    <van-loading v-show="isLoading" type="spinner" color="#1989fa" vertical>登录中...</van-loading>
  </div>
</template> 

<script lang="ts" setup>
import { onMounted, reactive,ref, watch,getCurrentInstance  } from 'vue'
import { useStore } from 'vuex'
import { useRouter,useRoute } from 'vue-router'
import * as type from '@/types'
import { Login,sendSMS } from 'api/user'
import { Toast } from 'vant'



const router = useRouter()
const route = useRoute()
const store = useStore()
const isLoading = ref<boolean>(false)
//@ts-ignore
const { proxy } = getCurrentInstance()


const user = reactive<type.Login>({
    mobile:"17090086870",
    code:"246810"
})


let isCountDownShow = ref<boolean>(false)
let isSendSmsLoading = ref<boolean>(false)


const loginForm = ref<any>(null)


const formRules = reactive({
    mobile:[
        { required:true,message:"请输入手机号"},
        { pattern: /^1[3|5|7|8|9]\d{9}$/,message:"手机号格式错误"} 
    ],
    code:[{required:true,message:"请输入验证码"},{ pattern:/^\d{6}$/,message:"请输入验证码"}]
})


watch(()=> route,(to,form,next) => {
    console.log(to,form,next)
})

onMounted(() => {
   let user =  store.state.user.user

   console.log("login:",user)
})

const onSendSMS = async () => {

    try {
        await loginForm.value.validate('mobile')

        isSendSmsLoading.value = true

        const resp = await sendSMS(user.mobile)
        isCountDownShow.value = true
        Toast({message:"验证码发送成功!",type:'success',position:'top'})
    } catch (error) {
        let message = ""

        if(error && error.response && error.response.status === 429) {
            message = "发送太频繁了,请稍后重试"
        } else if (error.name == 'mobile') {
            message = error.message
        } else {
            message = "未知错误,请稍后重试"
        }
        Toast({type:'fail',message:error,position:'top'})
    }

    isSendSmsLoading.value = false
}

const onLogin = async () => {

    // Toast.loading({
    //     message:"登录中...",
    //     forbidClick:true,  //禁止背景点击
    //     duration: 0
    // })

    isLoading.value = true
    try {
        const resp = await Login(user)

        if(resp === undefined) {
            throw new Error("登录失败")
        }
        isLoading.value = false
        Toast.success("登录成功")


        if(resp && resp.data) {
            let { data } = resp
            store.commit("setToken",data.data)
        }

        router.back()
    } catch (err) {
        isLoading.value = false
        Toast.fail("登录失败,手机号或验证码错误!")
    }
}

const onFailed = async (error:any)  => {
    if(error.errors[0]) {
        Toast({
            type:'fail',
            message:error.errors[0].message,
            position:'top'
        })
    }
}



</script>

<style lang="scss" scoped>
    .login-container {
        .send-btn {
            width: 76px;
            height: 23px;
            border:none;
            background-color:#ededed;
            .van-button__text {
                font-size:11px;
                color: #666666;
            }
        }
        .login-btn-wrap {
            padding: 26px 16px;
            
            .login-btn {
                border:none;
                background: #6db4fb!important;
                .van-button__text {
                    font-size:15px;
                }
            }
        }
    }
</style>